package com.sxt.common.handler;

import com.sxt.common.BussiException;
import com.sxt.common.CodeMsg;
import com.sxt.common.Result;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @description: 全局异常处理器
 * @author: Mr.xx
 * @date: 2021/3/6 18:58
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    @ResponseBody
    public Object handlerException(Exception excption) {

        //打印异常
        excption.printStackTrace();

        //判断是否是程序员自己定义的异常消息
        if (excption instanceof BussiException) {
            BussiException bussiException = (BussiException) excption;
            return new Result(bussiException);
        }

        //shiro异常
        if (excption instanceof ShiroException) {
            if (excption instanceof UnknownAccountException) {
                return  new Result(CodeMsg.USER_USER_PASSWORD_ERROR);
            }
            if (excption instanceof AuthenticationException) {
                return new Result(CodeMsg.USER_NOT_HAVE_PERMISSION_ERROR);
            }
        }

        //发生的其他异常
        return new Result(CodeMsg.ERROR);
    }
}
